import { 
    fetchNotifications, 
    markNotificationAsRead,
    markAllNotificationsAsRead 
  } from '@/api/notification'
  
  const state = {
    notifications: [],
    unreadCount: 0,
    loading: false,
    error: null
  }
  
  const getters = {
    getUnreadNotifications: (state) => {
      return state.notifications.filter(notification => !notification.read)
    }
  }
  
  const mutations = {
    SET_NOTIFICATIONS(state, notifications) {
      state.notifications = notifications
      state.unreadCount = notifications.filter(n => !n.read).length
    },
    ADD_NOTIFICATION(state, notification) {
      state.notifications.unshift(notification)
      if (!notification.read) {
        state.unreadCount++
      }
    },
    MARK_NOTIFICATION_AS_READ(state, notificationId) {
      const notification = state.notifications.find(n => n.id === notificationId)
      if (notification && !notification.read) {
        notification.read = true
        state.unreadCount--
      }
    },
    MARK_ALL_AS_READ(state) {
      state.notifications.forEach(notification => {
        notification.read = true
      })
      state.unreadCount = 0
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_ERROR(state, error) {
      state.error = error
    }
  }
  
  const actions = {
    async fetchNotifications({ commit }, params = {}) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const notifications = await fetchNotifications(params)
        commit('SET_NOTIFICATIONS', notifications)
        return notifications
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async markNotificationAsRead({ commit }, notificationId) {
      try {
        await markNotificationAsRead(notificationId)
        commit('MARK_NOTIFICATION_AS_READ', notificationId)
      } catch (error) {
        console.error('Error marking notification as read:', error)
      }
    },
    
    async markAllNotificationsAsRead({ commit }) {
      try {
        await markAllNotificationsAsRead()
        commit('MARK_ALL_AS_READ')
      } catch (error) {
        console.error('Error marking all notifications as read:', error)
      }
    }
  }
  
  export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
  }